package com.vma.jifu.controller;

import com.jfinal.kit.HttpKit;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.vma.tools.MDA;
import com.vma.tools.StringUtils;
import com.vma.tools.wxGZH.CheckUtil;
import com.vma.tools.wxGZH.JsApiTicket;
import com.vma.tools.wxGZH.WxGzhUtils;
import com.vma.tools.wxPay.PayConstant;
import com.vma.tools.wxPay.WxPay;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * Created by chenzui on 2017/8/2.
 */
public class WxCheckController extends BaseController {
    private Cache cache = Redis.use("xjhRedis");

    public void check(){
        String signature = getPara("signature");
        String timestamp = getPara("timestamp");
        String nonce = getPara("nonce");
        String echostr = getPara("echostr");
        if(CheckUtil.checkSignature(signature, timestamp, nonce)){
            System.out.println("success");
            renderText(echostr);
        }else {
            System.out.println("error");
            renderText(echostr);
        }
    }

//    wx.config({
//        debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
//                appId: '', // 必填，公众号的唯一标识
//                timestamp: , // 必填，生成签名的时间戳
//        nonceStr: '', // 必填，生成签名的随机串
//                signature: '',// 必填，签名，见附录1
//                jsApiList: [] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
//    });
    public void sign(){
        String url = getPara("url");
        Map result = new HashMap();
        String wxAccessToken =  cache.get("wx_access_token");
        if(StringUtils.isEmpty(wxAccessToken)){
            wxAccessToken = WxGzhUtils.globalAccessToken();
            cache.setex("wx_access_token", MDA.REDIS_EXPIRE_TIME,wxAccessToken);

        }
        String jsApiTicketStr =  cache.get("wx_jsApi_tikcet");
        if(StringUtils.isEmpty(jsApiTicketStr)){
            JsApiTicket jsApiTicket = WxGzhUtils.getTicket(wxAccessToken);
            jsApiTicketStr = jsApiTicket.getTicket();
            cache.setex("wx_jsApi_tikcet", MDA.REDIS_EXPIRE_TIME, jsApiTicketStr);
        }

        HashMap<String, String> paramMap = new HashMap<String, String>();
        String noncestr = WxPay.getRandomString(32);
        String timestamp = (System.currentTimeMillis() / 1000+"");
        paramMap.put("nonce_str", noncestr); // 随机数
        paramMap.put("jsapi_ticket",jsApiTicketStr);
        paramMap.put("timestamp", timestamp);
        paramMap.put("url",url);
//        System.out.println(paramMap);
        String signature = createSign(paramMap);
        result.put("appId",WxGzhUtils.appId);
        result.put("timestamp",timestamp);
        result.put("nonceStr",noncestr);
        result.put("signature",signature);
        renderRes(result);

    }

//    public static String getRandomString(int length) {
//        StringBuffer buffer = new StringBuffer("0123456789abcdefghijklmnopqrstuvwxyz");
//        StringBuffer sb = new StringBuffer();
//        Random random = new Random();
//        int range = buffer.length();
//        for (int i = 0; i < length; i++) {
//            sb.append(buffer.charAt(random.nextInt(range)));
//        }
//        return sb.toString();
//    }

    private String createSign(Map paramMap){
        //注意这里参数名必须全部小写，且必须有序
        String string1 = "jsapi_ticket=" + paramMap.get("jsapi_ticket").toString() +
                "&noncestr=" + paramMap.get("nonce_str").toString() +
                "&timestamp=" + paramMap.get("timestamp").toString() +
                "&url=" + paramMap.get("url").toString();
//        System.out.println(sb.toString());
        return getSha1(string1);
    }
    private String getSha1(String str) {
        Map<String, String> ret = new HashMap<String, String>();
        String signature = "";


        System.out.println(str);

        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(str.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return signature;

    }
    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }
}
